import { agreementAccountFromTgStorage } from '~/components-business/auth/CreateAccountFromTg.vue';
import { useAuthed } from '~/composables/useAuthed';
import cs from '~/composables/useCS';
import { useAppSocket } from '~/modules/socket/useAppSocket';
import { jsBridge } from '~/utils/defines';

export const useUserStore = defineStore('user', () => {
  const authed = useAuthed();
  const appSocket = useAppSocket();

  const userInfoQry = useQuery({
    enabled: authed,
    queryKey: [apis.apiUserInfo.id],
    queryFn: () => apis.apiUserInfo(undefined),
    refetchInterval: 10 * 1000,
    refetchOnWindowFocus: true,
  });
  const userInfo = computed(() => userInfoQry.data.value);
  // 用户类型 1临时用户（无帐变）2意向用户（只有测试币帐变）3有效用户（有正式币或充值）4高净值客户（充值满10万）5超级大户（充值满100万）6（风险客户：洗钱嫌疑，薅羊毛，找漏洞）7试玩用户(不统计报表)
  const userType = computed(() => userInfo.value?.type);
  const verified = computed(() => {
    const _userInfo = userInfo.value;

    if (authed.value && _userInfo) {
      return {
        email: !!(_userInfo.email && _userInfo.email_verified),
        authenticator: !!_userInfo.enable_authenticator,
      };
    }
  });

  appSocket.receive('USER_INFO_RESP', 'UserDetail', () => {
    userInfoQry.refetch();
  });

  appSocket.receive('USER_LEVEL_UPGRADE_RESP', 'UserDetail', () => {
    queryClient.invalidateQueries({ queryKey: [apis.apiLevelInfo.id], exact: false });
    userInfoQry.refetch();
  });

  async function logout() {
    jsBridge.post('logout', { uid: userInfo.value?.uid, email: userInfo.value?.email });
    await apis.apiAuthLogout({});
    cs.clear();
    agreementAccountFromTgStorage.remove();
  }

  watch(userInfoQry.data, (data) => {
    jsBridge.uid = data?.uid || '';
    jsBridge.email = data?.email || '';
  }, { immediate: true });

  return {
    /** 用户信息查询器 */
    userInfoQry,
    /** 用户信息 */
    userInfo,
    /** 用户类型 */
    userType,
    /** 验证状态 */
    verified,
    /** 登出 */
    logout,
  };
});
